package com.pkk.penguin.components.starter.rpc.crypto.service;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSONObject;
import java.io.InputStream;

/**
 * @author luffy
 * @description: RSA
 * @date 2019-11-15 17:28
 */
public class RsaCryptService implements CryptoService {
  private RSA rsa ;

  public RsaCryptService(String privateKey,String publicKey){
    this.rsa = new RSA(privateKey,publicKey);
  }

  /**
   * @Author luffy
   * @Description 加密
   * @Param str
   * @Param keyType
   * @Return java.lang.String
   * @Date 2019-11-13 10:44
   */
  private String encryptForKey(String str, KeyType keyType) {
    return rsa.encryptBcd(str, keyType);
  }

  public String encryptForPublikKey(String string) {
    return this.encryptForKey(string, KeyType.PublicKey);
  }

  public String encryptForPrivateKey(String string) {
    return this.encryptForKey(string, KeyType.PrivateKey);
  }

  /**
   * @Author luffy
   * @Description 解密
   * @Param encrypt
   * @Param keyType
   * @Return java.lang.String
   * @Date 2019-11-13 10:56
   */
  private String decryptForKey(String encrypt, KeyType keyType) {
    return rsa.decryptStr(encrypt, keyType);
  }

  public String decryptForPublicKey(String string) {
    return this.decryptForKey(string, KeyType.PublicKey);
  }

  public String decryptForPrivateKey(String string) {
    return this.decryptForKey(string, KeyType.PrivateKey);
  }

  @Override
  public String encrypt(String string) {
    return this.encryptForPrivateKey(string);
  }

  @Override
  public String encrypt(Object object) {
    return this.encryptForPrivateKey(JSONObject.toJSONString(object));
  }

  @Override
  public byte[] encrypt(byte[] bytes) {
    return this.rsa.decrypt(bytes,KeyType.PrivateKey);
  }

  @Override
  public byte[] encrypt(InputStream is) {
    return this.rsa.decrypt(is,KeyType.PrivateKey);
  }

  @Override
  public String decrypt(String string) {
    return this.decryptForPrivateKey(string);
  }

  @Override
  public byte[] decryptForByte(String string) {
    return StrUtil.bytes(this.decrypt(string), CharsetUtil.CHARSET_UTF_8);
  }

  @Override
  public byte[] decrypt(byte[] bytes) {
    return this.rsa.decrypt(bytes,KeyType.PrivateKey);
  }

  @Override
  public byte[] decrypt(InputStream is) {
    return this.rsa.decrypt(is,KeyType.PrivateKey);
  }
}
